require("./requires");
var crypto = require('../utils/crypto');
var express = require('express');
var db = require('../utils/db');
var http = require("../utils/http");

var app = express();
var configs = require("./../ServerConfig.js");
db.init(configs.mysql());

var config = configs.account_server();

app.listen(config.CLIENT_PORT);

var hallAddr = config.HALL_IP  + ":" + config.HALL_CLIENT_PORT;

function send(res,ret){
	var str = JSON.stringify(ret);
	res.send(str)
}

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/register',function(req,res){
	var account = req.query.account;
	var password = req.query.password;

	var fnFailed = function(){
		send(res,{errcode:1,errmsg:"account has been used."});
	};

	var fnSucceed = function(){
		send(res,{errcode:0,errmsg:"ok"});	
	};

	db.is_user_exist(account,function(userid,exist){
		if(exist){
			db.create_account(account,password,function(ret){
				if (ret) {
					fnSucceed();
				}
				else{
					fnFailed();
				}
			});
		}
		else{
			fnFailed();
			console.log("account has been used.");			
		}
	});
});

var VERSION = 20161204;

app.get('/get_version',function(req,res){
	var ret = {
		version:VERSION,
	}
	send(res,ret);
});

app.get('/get_serverinfo',function(req,res){
	var devType = req.query.device;
	var webAddr = "";
	console.log("receive type == "+devType);
	if ("android"==devType)
	{
		webAddr = "http://www.yp6868.com";
	}
	else if ("ios"==devType)
	{
		console.log("receive type 2 == "+devType);
		webAddr = "http://www.yp6868.com";
	}
	console.log(webAddr);
	var ret = {
		version:VERSION,
		hall:hallAddr,
		appweb:webAddr,
	}
	send(res,ret);
});

app.get('/guest',function(req,res){
	var account = "guest_" + req.query.account;
	var sign = crypto.md5(account + req.ip + config.ACCOUNT_PRI_KEY);
	var ret = {
		errcode:0,
		errmsg:"ok",
		account:account,
		halladdr:hallAddr,
		sign:sign
	}
	send(res,ret);
});

app.get('/auth',function(req,res){
	var account = req.query.account;
	var password = req.query.password;

	db.get_account_info(account,password,function(info){
		if(info == null){
			send(res,{errcode:1,errmsg:"invalid account"});
			return;
		}

        var account = "vivi_" + req.query.account;
        var sign = get_md5(account + req.ip + config.ACCOUNT_PRI_KEY);
        var ret = {
            errcode:0,
            errmsg:"ok",
            account:account,
            sign:sign
        }
        send(res,ret);
	});
});

var appInfo = {
	Android:{
		appid:"wx7760c467ec57d20d",   //wx7760c467ec57d20d 新的 wxe39f08522d35c80c 原来的
		secret:"7c55a72926d3c6b0d96501bcd3285c8e", // 7c55a72926d3c6b0d96501bcd3285c8e 新的 fa88e3a3ca5a11b06499902cea4b9c01 原来的
	},
	iOS:{
		appid:"wx7760c467ec57d20d",  //wx7760c467ec57d20d 新的 wxcb508816c5c4e2a4 原来的
		secret:"7c55a72926d3c6b0d96501bcd3285c8e",	//7c55a72926d3c6b0d96501bcd3285c8e 新的 7de38489ede63089269e3410d5905038	原来的
	}
};

function get_access_token(code,os,callback){
	var info = appInfo[os];
	if(info == null){
		callback(false,null);
	}
	var data = {
		appid:info.appid,
		secret:info.secret,
		code:code,
		grant_type:"authorization_code"
	};

	http.get2("https://api.weixin.qq.com/sns/oauth2/access_token",data,callback,true);
}

function get_state_info(access_token,openid,callback){
	var data = {
		access_token:access_token,
		openid:openid
	};

	http.get2("https://api.weixin.qq.com/sns/userinfo",data,callback,true);
}

function create_user(account,name,sex,headimgurl,callback){
	var coins = 1000;
	var gems = 18;
	db.is_user_exist(account,function(userid,ret){
		if(!ret){
			db.get_max_userid(function(data){
				var userNewid = 105000;
				if (data != null)
				{
					++data.userid;
					userNewid = (data.userid>=105000)?data.userid:userNewid;
				}
				db.create_user(userNewid,account,name,coins,gems,sex,headimgurl,function(ret1,ret2){
					callback(ret1,ret2);
				});
			});
		}
		else{
			db.update_user_info(account,name,headimgurl,sex,function(ret2){
				callback(userid,ret2);
			});
		}
	});
};
app.get('/wechat_auth',function(req,res){
	var code = req.query.code;
	var os = req.query.os;
	console.log("account receive wechat_auth, code == "+code);
	if(code == null || code == "" || os == null || os == ""){
		return;
	}
	console.log("account receive wechat_auth, os == "+os);
	get_access_token(code,os,function(suc,data){
		if(suc){
			var access_token = data.access_token;
			var openid = data.openid;
			get_state_info(access_token,openid,function(suc2,data2){
				if(suc2){
					var openid = data2.openid;
					var nickname = data2.nickname;
					var sex = data2.sex;
					var headimgurl = data2.headimgurl;
					var account = "wx_" + openid;
					console.log("new user wei xin name == "+data2.nickname);
					create_user(account,nickname,sex,headimgurl,function(ret1,ret2){
						if (ret2 == true)
						{
							var sign = crypto.md5(account + req.ip + config.ACCOUNT_PRI_KEY);
							send(res,{
								errcode:0,
								errmsg:"ok",
								account:account,
								halladdr:hallAddr,
								sign:sign,
								name:nickname,
								sex:sex,
								headimgurl:headimgurl,
								userid:ret1});
							console.log("wechat_auth create user success!");
							console.log(" userid == " + ret1 + " account == "+account+" headimgurl == " + headimgurl);
						}
						else
						{
							console.log("create user failed!");
							send(res,{errcode:-1,errmsg:"create user failed!"});
						}
					});						
				}
			});
		}
		else{
			console.log("create user failed! unknown error");
			send(res,{errcode:-1,errmsg:"unkown err."});
		}
	});
});

app.get('/base_info',function(req,res){
	var userid = req.query.userid;
	db.get_user_base_info(userid,function(data){
		if (data != null)
		{
			var ret = {
				errcode:0,
				errmsg:"ok",
				name:data.name,
				sex:data.sex,
				headimgurl:data.headimg
			};
			send(res,ret);
			console.log("get base info success!");
			console.log(ret);
		}
		else
		{
			console.log("get base info no user data error");
			send(res,{errcode:-1,errmsg:"no user data."});
		}
	});
});


console.log("account server is listening on port " + config.CLIENT_PORT);